import random,hashlib,string,time,os
def randStr(num=8):
    salt = ''.join(random.sample(string.ascii_letters + string.digits, num))
    return salt
def warn(args):
    print("\033[1;31;40m"+str(args)+"\033[0m") 
def info(args):
    print("\033[1;32;40m"+str(args)+"\033[0m") 

def ROOT():
    if os.path.islink(__file__):
        return os.path.dirname(os.path.dirname(os.readlink(__file__)))
    else:
        return os.path.dirname(os.path.dirname(__file__))
def md5(string):
    import hashlib
    m=hashlib.md5()
    m.update(string)
    return m.hexdigest()
def hash(key,ts,nonce):
    return md5(key+ts+key+nonce)
nonces={}
def checkTime(timestamp,threshold=3000):
    return abs(int(time.time())-int(timestamp))<=threshold
   
def checkNonce(nonce,hourLimit=1):
   
    for key in nonces:
        if nonce in nonces[key]:
            return False
    curTime=time.localtime()            
    today=int(time.strftime("%d", curTime))        
    if len(nonces)>1:
        temp=nonces[today]
        nonces[today]=temp
        
    curHour=int(time.strftime("%H", curTime))
    if not (today in nonces):
        nonces[today]={}
        nonces[today][curHour]=[nonce]
    else:
        if not(curHour in nonces[today]):
            nonces[today][curHour]=[nonce]
        else:    
            nonces[today][curHour].append(nonce)     
    if len(nonces[today][curHour])>hourLimit:
        if ((curHour-hourLimit) in nonces[today]):
            del(nonces[today][curHour-hourLimit])
    return True    